<template>
    <el-container class="chat-container">
      <el-aside class="sidebar">
        <el-menu class="el-menu-vertical-demo" @select="handleSelect">
    <el-menu-item 
        v-for="client in clients" 
        :key="`${client.id}-${client.role}`" 
        :index="`${client.id}-${client.role}`"
    >
        <img :src="client.avatar" class="avatar" />
        <span class="client-name">{{ client.nickName }}</span>
        <span class="unread-count" v-if="client.scount !== 0">{{ client.scount }}</span>
    </el-menu-item>
</el-menu>
      </el-aside>
      
      <el-container class="chat-content">
        <el-header class="chat-header">
          <span v-if="isChat==null">欢 迎 使 用 客 服 系 统 ！</span>
          <span v-if="isChat=='user'">乘客--  {{ clientNickName }}</span>
          <span v-if="isChat=='driver'">司机--  {{ clientNickName }}</span>
        </el-header>
        
        <el-main class="chat-main">
          <div ref="chatWindow" class="chat-window">
            
            <div    v-show="chatFooter"    v-for="(message, index) in showMessages" :key="index" class="message" :class="{'user': message.role === 'user'||message.role === 'driver', 'agent': message.role === 'staffService'}">
              <img v-if="message.role === 'user'||message.role === 'driver'" :src="clientImg"  alt="User Avatar" class="avatar">
              <div :class="['message-content', message.role]">
                {{ message.msg }}
              </div>
              <img v-if="message.role === 'staffService'" src="http://110.41.38.161:9000/ruoyi/2024/9/20/photo11.gif"  alt="Agent Avatar" class="test-demo">
            </div>
  
            <div v-show="!chatFooter" style="margin-top:100px;font-size:25px"> 客服上班时间 9:00 - 18:00 , 祝您上班愉快！</div>
          </div>
            
          <el-footer class="chat-footer" v-show="chatFooter">
            <!-- 表情按钮 -->
            <span class="emoji-btn" @click="toggleEmojiPicker">
                <span>{{emojiIcon}}</span>
            </span>
            <!-- 表情选择栏 -->
            <div class="emoji-picker" v-show="showEmojiPicker">
                <div class="emoji-container">
                    <div v-for="(items, index) in emojData" :key="index" class="emoji-row">
                        <div v-for="(item, index) in items" :key="index" class="emoj_parent" @click="tuchEmoj(item, index)">
                            <span class="emoj_conn">{{ item }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <el-input
                v-model="newMessage"
                placeholder="输入消息"
                @keyup.enter.native="sendMessage"
                suffix-icon="el-icon-chat-dot-round"
                clearable
                style="width:95%;margin-left:10px"
            ></el-input>
        </el-footer>

        </el-main>
      </el-container>
    </el-container>
  </template>
   <script>
   import { updateStatus } from "@/api/staff";
   import store from '@/store'
  export default {
  
    created(){
       this.staffServiceId= store.getters.userId;
       console.log("这是你的客服id",this.staffServiceId)
     
     this.connectWebSocket();
    },
    data() {
      return {
        isChat:null,
        clientNickName:'',
        emojData: [
					['🤞', '👍', '👏', '❤', '😁', '🖐', '😀', '😃'],
					['😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇'],
					['🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗'],
					['😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨'],
					['🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒', '😞'],
					['😔', '😟', '😕', '🙁', '😣', '😖', '😫', '😩'],
					['🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯'],
					['😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓'],
					['🤗', '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑'],
					['😬', '🙄', '😯', '😦', '😧', '😮', '😲', '😴'],
					['🤤', '😪', '😵', '🤐', '🥴', '🤢', '🤮', '🤧'],
					['😷', '🤒', '🤕', '🤑', '🤠', '👻', '🐧']
				],
        emojiIcon:'😇',
        showEmojiPicker:false,
        clients: [
          {id: 1, name: 'User A', img: 'http://110.41.18.31:9009/ruoyi/2024/09/13/6_20240913184613A001.PNG', role: 'user'},
          { id:1, name: 'driver 1', img: 'http://110.41.18.31:9009/ruoyi/2024/09/13/6_20240913184613A001.PNG',role:'driver' },
        ],
        showMessages: [],
        
        
        staffServiceId:null,
        newMessage: '',
        webSocket: null,// 用于存储WebSocket连接
        sendMsg:{},
        currentClientId: null,
        currentClientRole: null,
        acceptorRole:'',
        chatFooter:false,
        clientImg:'',
      };
    },
    computed: {
     /*  currentMessages() {
        return this.messages[this.currentClientId] || [];
      } */
    },
    mounted() {
       // 组件挂载后建立WebSocket连接
    },
    beforeDestroy() {
      if (this.webSocket) {
        this.webSocket.close(); // 组件销毁前关闭WebSocket连接
        console.log("断开webscoket")
     }
    },
    methods: {
      tuchEmoj(item,index) {
				this.newMessage = this.newMessage + item;
			},
      toggleEmojiPicker() {
				if(this.showEmojiPicker){
					this.emojiIcon='😇'
				}else{
					this.emojiIcon='😄'
				}
				this.showEmojiPicker = !this.showEmojiPicker;
			},
      // webscoket
      connectWebSocket() {
        const wsUrl = 'ws://127.0.0.1:11199/trip-ws/websocket'; // 替换为您的WebSocket服务器地址
        this.webSocket = new WebSocket(wsUrl);
        console.log("准备连接")
        this.webSocket.onopen = () => {
          console.log('WebSocket连接已打开');
         this.refreshMsg();
        };
  
        this.webSocket.onmessage = (event) => {
          console.log("收到消息",event.data)
  
          console.log("-------------------------------------")
          
           const message = JSON.parse(event.data); 
         
          /*  localStorage.setItem("staffServiceId",message.staffServiceId) */
         /*  console.log("8888",message) */
          
            //当收到消息后，如果在发送方是客服当前窗口直接更新 ，不是的话只提示有客户来消息了。

            this.clients=message.linkClientList
            //客户/司机发消息， 被动接收时候。
            if(Array.isArray(message.callCenterDtoList) && message.callCenterDtoList.length > 0){
              let last_record = message.callCenterDtoList[message.callCenterDtoList.length - 1]
              let  role_value = last_record["role"]
              let  id_value ;
              if(role_value=="user"){
                id_value = last_record['userId']
              }else if(role_value=="driver"){
                id_value = last_record['driverId']
              }else {
                if(message.callCenterDtoList.length==0){
                  this.showMessages=[];
                }else{
                  this.showMessages=message.callCenterDtoList;
                }
               
                return;
              }
              console.log("最后一条角色："+role_value +"--------最后的id"+ id_value)
              if(this.currentClientRole==role_value&&this.currentClientId==id_value){ //符合当前窗口
                if(message.callCenterDtoList.length==0){
                  this.showMessages=[];
                }else{
                  this.showMessages=message.callCenterDtoList;
                }
              }
            }
           /*   */
          
          this.$nextTick(() => {
            const chatWindow = this.$refs.chatWindow;
            chatWindow.scrollTop = chatWindow.scrollHeight;
          });
        };
        this.webSocket.onerror = (error) => {
          console.error('WebSocket出现错误', error);
        };
         this.webSocket.onclose = () => {
          console.log('WebSocket连接已关闭');
          // 根据需要重新连接或处理断开连接的情况
        }; 
      },
      refreshMsg(){
        let message = {
            role:'staffService',
            type:'上线',
            staffServiceId:this.staffServiceId,
          }
          this.webSocket.send(JSON.stringify(message))
      },
      inputMsg(){
        console.log("发送！")
      },
      sendMessage() {
        console.log("客服发消息")
        this.showEmojiPicker=false
        if (this.newMessage.trim()) {
          // 发送消息到服务器
          if(this.currentClientRole=='driver'){
            let message = {
              staffServiceId:this.staffServiceId,
              msg: this.newMessage,
              type:'发送消息',
              userId:null,
              driverId:this.currentClientId,
              role:"staffService"
            }
          this.webSocket.send(JSON.stringify(message));
          }else{
            let message = {
              staffServiceId:this.staffServiceId,
              msg: this.newMessage,
              type:'发送消息',
              userId:this.currentClientId,
              driverId:null,
              role:"staffService"
            }
          this.webSocket.send(JSON.stringify(message));
          }
         
        
          this.newMessage = '';
          this.$nextTick(() => {
            const chatWindow = this.$refs.chatWindow;
            chatWindow.scrollTop = chatWindow.scrollHeight;
          });
        }
      },
      //拉取历史记录
      handleSelect(index) {
        
      
        this.chatFooter=true
        // 分割索引字符串来获取 id 和 role
      const parts = index.split('-');
      const clientId = parts[0];
      const clientRole = parts[1];
     
      // 根据 id 和 role 查找对应的客户端对象
      const selectedClient = this.clients.find(client => client.id.toString() === clientId && client.role === clientRole);
  
      
        if (selectedClient) {
          selectedClient.scount=0;
          //访问数据库--修改状态  //未读->需要重置未读，且 数据库修改 读消息状态 0->1  
          let record={
            role:selectedClient.role,
            id: selectedClient.id,
            staffServiceId:this.staffServiceId
          }
          updateStatus(record).then(res => {
                console.log("更改状态的回调",res)
            });
          
          console.log("this.clients",this.clients)
          this.currentClientId = selectedClient.id;
          this.currentClientRole = selectedClient.role;
          this.clientImg=selectedClient.avatar
          this.clientNickName=selectedClient.nickName;
          this.isChat=selectedClient.role;
          console.log("id", this.currentClientId)
          console.log("role",this.currentClientRole)
          //拉取历史-webscoket
          // 设置定时器，延迟 2 秒后发送 WebSocket 消息
 
        let message;
        if (this.currentClientRole === 'driver') {
            message = {
                staffServiceId: this.staffServiceId,
                type: '读取历史记录',
                userId: null,
                driverId: this.currentClientId,
                role: "staffService"
            };
        } else {
            message = {
                staffServiceId: this.staffServiceId,
                type: '读取历史记录',
                userId: this.currentClientId,
                driverId: null,
                role: "staffService"
            };
        }
        this.webSocket.send(JSON.stringify(message));
        setTimeout(() => {
          selectedClient.scount=0;
    }, 500); // 延迟 0.5 秒
           
        }
      },
      handleDelete(clientId) {
        /* const index = this.clients.findIndex(client => client.id === clientId);
        if (index !== -1) {
          this.clients.splice(index, 1);
          delete this.messages[clientId];
          if (this.currentClientId === clientId) {
            this.currentClientId = 1; // 默认切换到第一个客户
          }
        } */
      }
    }
  };
  </script>
    
    <style scoped>
    .chat-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f0f2f5;
    }
    
    .sidebar {
      background-color: #ffffff;
      border-right: 1px solid #ddd;
      padding: 15px;
      box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
      height: calc(100vh - 190px); /* Height adjusted to match chat window */
      overflow-y: auto;
    }
    
    .chat-content {
      display: flex;
      flex-direction: column;
      width: 80%;
      max-width: 900px;
      height: 80vh;
      background-color: #ffffff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    
    .chat-header {
      background-color: #409EFF;
      color: white;
      padding: 10px;
      text-align: center;
      font-size: 18px;
      font-weight: bold;
      border-bottom: 1px solid #ddd;
    }
    
    .chat-main {
      display: flex;
      flex-direction: column;
      height: calc(100% - 80px); /* Adjust based on header and footer height */
      padding: 10px;
    }
    
    .chat-window {
      flex: 1;
      overflow-y: auto;
      padding: 10px;
      border: 1px solid #ddd;
      background-color: #f9f9f9;
    }
    
    .message {
      margin-bottom: 10px;
      font-size: 14px;
    }
    
    .message .agent{
      text-align: left;
      color: #409EFF;
    }
    
    .message .user  {
      text-align: right;
      color: #67C23A;
    }
    
    .message .system {
      text-align: center;
      color: #909399;
    }
    
    .chat-footer {
      background-color: #f5f5f5;
      padding: 10px;
      border-top: 1px solid #ddd;
    }
    .message p{
      margin-top:20px;
  
    }
    
    .test-demo{
      width: 40px;
      height: 40px;
      border-radius: 50%;
      object-fit: cover;
      margin-left:15px;
    }
  
    .message {
      display: flex;
      margin-bottom: 10px;
      align-items: center;
    }
  
    .message-content {
      background-color: #f0f0f0;
      border-radius: 12px;
      padding: 10px;
      max-width: 60%; /* 根据需要调整气泡的最大宽度 */
      word-wrap: break-word; /* 确保文本在气泡内换行 */
    }
  
    .message.user {
      justify-content: flex-start; /* 用户消息靠左对齐 */
    }
  
    .message.agent {
      justify-content: flex-end; /* 客服消息靠右对齐 */
    }
  
    .message.system{
      display: flex;
      justify-content: center; /* 客服消息靠右对齐 */
    }
  
    .message.user .message-content {
      background-color: #409EFF;
      color: white;
      border-top-left-radius: 0; /* 取消左侧圆角 */
    }
  
    .message.agent .message-content {
      background-color: #67C23A;
      color: white;
      border-top-right-radius: 0; /* 取消右侧圆角 */
    }
  
    /* 头像位置调整 */
    .message.user .avatar {
      margin-right: 10px; /* 用户消息头像右边距 */
    }
  
    .message.agent .avatar {
      margin-left: 10px; /* 客服消息头像左边距 */
    }
    /*未读的样式----------*/
    
    .el-menu-item {
    display: flex;
    align-items: center;
    padding: 10px 15px;
}

.avatar {
    margin-right: 10px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}

.client-name {
  flex-grow: 1; /* 使名称占用剩余空间 */
    text-align: center; /* 中间对齐 */
    white-space: nowrap; /* 不换行 */
}

.unread-count {
  display: flex;
    justify-content: center;
    align-items: center;
    width: 20px; /* 设置宽度 */
    height: 20px; /* 设置高度 */
    border-radius: 50%; /* 圆形 */
    color: white;
    background-color: red;
    font-size: 12px;
    margin-left: 8px;
    text-align: center; /* 文本居中 */
}
  
  .unread-count:hover {
    opacity: 0.8;
  }
  
  /* 如果未读数为0或不存在，则隐藏 */
  .unread-count:empty {
    display: none;
  }
  
  /* 当未读数超过99时的特殊样式 */
  .unread-count.overflow {
    overflow: hidden;
    width: 24px; /* 根据实际情况调整宽度 */
    text-overflow: ellipsis;
    white-space: nowrap;
  } 

 /* 表情包*/
 .emoji-picker {
    width: 50%; /* 调整宽度 */
    margin-left: 530px;
    position: absolute;
    bottom: 150px; /* 调整为距离输入框上方 */
    left: 0;
    background-color: #fff;
    border-top: 1px solid #ddd;
    padding: 10px;
    z-index: 20; /* 确保表情选择栏在其他元素之上 */
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* 可选：添加阴影以提高可见性 */
    display: flex;
    justify-content: center; /* 水平居中对齐 */
}

.emoji-container {
    display: flex;
    flex-wrap: wrap; /* 允许换行 */
    justify-content: center; /* 水平居中对齐 */
    overflow-y: auto; /* 允许垂直滚动 */
    max-height: 200px; /* 设置最大高度 */
}

.emoji-row {
    display: flex;
    flex-direction: row;
    justify-content: center; /* 水平居中对齐 */
}

.emoj_parent {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 4px;
    cursor: pointer; /* 鼠标悬停时显示手型光标 */
}

.emoj_conn {
    font-size: 20px;
}

    </style>
    